package cn.baiyang.rocketmq.example;

import cn.baiyang.rocketmq.example.producer.ProducerExample;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import javax.annotation.Resource;

import org.apache.rocketmq.client.apis.ClientException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * @author hongzhu
 * @version V1.0
 * @since 2023-07-27 09:45
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "rocketmq-java", value = {"producer.topics"})
public class MessageSenderJob implements CommandLineRunner {
    private final AtomicLong counter = new AtomicLong(0);

    @Resource
    private ProducerExample producerExample;

    @Override
    public void run(String... args) throws Exception {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                String messageId = null;
                try {
                    messageId = producerExample.send("{\"name\": \"zhangsan\", \"phone\": \"13305712345\"}");
                    log.info("{}. Message is Sent, Id={}", counter.incrementAndGet(), messageId);
                } catch (ClientException e) {
                    throw new RuntimeException(e);
                }
            }
        }, 1, 30, TimeUnit.SECONDS);
    }

}
